<template>
  <div class="high">
    <el-popover
      placement="bottom"
      width="184"
      ref="webchatLimit"
      v-model="isShowLimit"
      trigger="click">
      <el-form>
        <el-form-item>
          <span class="font12">{{$t('webchat.sessionLimit')}}</span>
          <div class="webchatLimitSelect">
            <el-select size="mini" class="chat_limit" filterable v-model.trim="webchatLimit.value" placeholder="1" @change="changeLimitFun">
              <el-option v-for="(item, index) in webchatLimit.options" :key="index" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
    </el-popover>
    <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.webchatLimitNotice && !isCommerce">
      <div class="novice-circle-group " :class="isSessionInvitation ? 'noticeOne' : 'noticeTwo'">
        <div class="novice-circle4"></div>
        <div class="novice-circle3"></div>
        <div class="novice-circle2"></div>
        <div class="novice-circle1"></div>
      </div>
      <div style="position: absolute;top: 0px;left:17px ;padding-bottom: 10px;z-index: 100;">
        <novice-boot
          NoviceKey="webchatLimitNotice"
          :NoviceArr="[{title: '', text: $t('webchat.leaveMsgBubble')}]"
          @updateGuidanceSuccess="updateGuidanceSuccess"
        ></novice-boot>
      </div>
    </div>
    <el-tooltip class="item" effect="dark" :content="$t('webchat.sessionLimit')" placement="top" v-if="!isCommerce">
      <el-button class="iconfont icon-huihuashangxianshezhi searchButton" type="text" v-popover:webchatLimit></el-button>
    </el-tooltip>
    <el-popover
      ref="popoverTime"
      width="730"
      placement="bottom"
      trigger="click"
      :offset="100">
      <el-form :inline="true" label-position="top"  class="high-ranking-search">
        <div class="font12 time_search_box">
          <div class="flex3">
            <div class="search_title">{{$t("webchat.visitorLastReply")}}</div>
            <div v-for="(item, index) in groupCustomer.list" class="groupLi">
              <label class="label-box">
                <input type="checkbox" v-model.trim="item.checked" @change="changeCustomerLabel(index, item.checked)"><span class="label-text">{{item.name}}</span>
              </label>
            </div>
            <div class="groupLi groupLiText">
              <input type="text" v-model.trim="groupCustomer.customize" @focus="switchCustomerTime" :placeholder="'1-9999'" maxlength="4"/>{{$t('webchat.timeBefore', { time: ''})}}
            </div>
          </div>
          <div class="flex3">
            <div class="search_title">{{$t("webchat.agentLastReply")}}</div>
            <div v-for="(item, index) in groupAgent.list" class="groupLi" :key="item.time">
              <label class="label-box">
                <input type="checkbox" v-model.trim="item.checked" @change="changeAgentLabel(index, item.checked)"><span class="label-text">{{item.name}}</span>
              </label>
            </div>
            <div class="groupLi groupLiText">
              <input type="text" v-model.trim="groupAgent.customize" @focus="switchAgentTime" :placeholder="'1-9999'" maxlength="4"/>{{$t('webchat.timeBefore', { time: ''})}}
            </div>
          </div>
        </div>
        <el-form-item class="btn-group">

          <el-button class="primary_btn" @click="resetFormData(true)">{{$t("public.reset")}}</el-button>
          <el-button type="primary" class="primary_btn" @click="submitFormData">{{$t("public.search")}}</el-button>
        </el-form-item>
      </el-form>
    </el-popover>
    <el-tooltip  class="item" effect="dark" :content="$t('webchat.timeSearch')" placement="top">
      <el-button v-if="!isCommerce" class="iconfont icon-sousuo searchButton" type="text" v-popover:popoverTime @click="visible = !visible"></el-button>
    </el-tooltip>
    <el-tooltip  class="item" effect="dark" :content="$t('webchat.SessionOrdering')" placement="top">
      <el-dropdown @command="handleChangeListSort" trigger="click" class="searchButton" size="small">
        <el-button class="iconfont icon-paixu" type="text"></el-button>
        <el-dropdown-menu slot="dropdown"  style="overflow: hidden">
          <el-dropdown-item v-for="(type, index) in ListSortTypes"
            :disabled="type.disabled"
            :key="index"
            class="ListdropItem" :command="type.value"
            :class="{dropActive: ListSortType === type.value}">
            {{type.name}}
            <i class="iconfont icon-xuanze" style="float: right;" v-show="ListSortType === type.value"></i>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-tooltip>
    <el-tooltip v-if="isSessionInvitation && !isCommerce"
                class="item" effect="dark" :content="$t('webchat.activeSession')" placement="top">
      <el-button
                 class="iconfont icon-zhudongyaoqing searchButton" type="text"
                 @click.stop="openpopConversation()"></el-button>
    </el-tooltip>
  </div>
</template>
<script>
  import {deepClone, innerHtmlChannelColor} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  import {SET_SUCCESS} from '@/store/mutation-types'
  import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
  export default {
    name: 'AdvancedSearch',
    /**
     * [props 该组件所需要的参数]
     * @type {
     *   type        业务类型
     *   typeType    业务tab
     * }
     */
    data () {
      return {
        visible: false,
        groupCustomer: {
          list: [
            {name: this.$t('webchat.timeBefore', {time: 5}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 10}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 15}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 20}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 25}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 30}), checked: false}
          ],
          customize: ''
        },
        groupAgent: {
          list: [
            {name: this.$t('webchat.timeBefore', {time: 5}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 10}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 15}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 20}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 25}), checked: false},
            {name: this.$t('webchat.timeBefore', {time: 30}), checked: false},
            {name: this.$t('webchat.unReadChat'), checked: false}
          ],
          customize: ''
        },
        sessionInvitation: '',
        ListSortTypes: [
          {name: this.$t('webchat.lastCustomerMsg'), value: 'lastCustomerMsgTimeStamp'},
          {name: this.$t('webchat.accessOrder'), value: 'beginTime'},
          {name: this.$t('webchat.visitorsWaitTime'), value: 'startWaitTimerStamp'}
        ],
        ListSortType: '',
        isShowLimit: false,
        getNoviceKeyStatus: {}
      }
    },
    props: {
      resetSearch: Boolean,
      webchatLimit: Object,
      isCommerce: Boolean // true为电商版 否则是标准版
    },
    computed: {
      isSessionInvitation () {
        return this.sessionInvitation && this.sessionInvitation != 0 && !this.$store.state.session.user.isAdmin
      }
    },
    watch: {
      'resetSearch': 'resetFormData'
    },
    methods: {
      // 引导状态更新
      updateGuidanceSuccess () {
        let guidance = this.$getCache('guidance')
        this.getNoviceKeyStatus = guidance || {'webchatLimitNotice': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
      },
      handleChangeListSort (type) {
        this.ListSortType = type
        let currentUser = this.$store.state.session.user.loginName + '@' + this.$store.state.session.account.name
        window.localStorage.setItem(currentUser + '/sortType', type)
        this.$store.commit('webchat/SET_SORTTYPE', {type: type})
        this.$store.commit('webchat/SORTLISTBY_TYPE')
      },
      switchCustomerTime () {
        this.groupCustomer.list.forEach((item) => {
          item.checked = false
        })
      },
      switchAgentTime () {
        this.groupAgent.list.forEach((item, index) => {
          if (index !== 6) {
            item.checked = false
          }
        })
      },
      changeLimitFun (value) {
        let that = this
        this.$store.dispatch('updateCurrentUser', {'imDealCount': value.toString()}).then(() => {
          this.isShowLimit = false
          that.$store.commit(SET_SUCCESS, 'message.editSucess')
        })
      },
      resetFormData (data) {
        if (this.resetSearch || data) {
          this.groupAgent.list.forEach((item) => {
            item.checked = false
          })
          this.groupCustomer.list.forEach((item) => {
            item.checked = false
          })
          this.groupCustomer.customize = ''
          this.groupAgent.customize = ''
        }
      },
      openpopConversation () {
        // v22.1 增加打开会话邀请埋点
        const account = this.$store.state.session.account.account
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PE-打开会话邀请', account])
        this.$emit('inviteInfo')
      },
      submitFormData () {
        let match1 = checkform(this.groupCustomer.customize, 'Number3')
        let match2 = checkform(this.groupAgent.customize, 'Number3')
        if (match1) {
          this.$message.error(this.$t(match1))
          this.groupCustomer.customize = ''
          return
        }
        if (match2) {
          this.$message.error(this.$t(match2))
          this.groupAgent.customize = ''
          return
        }
        if (this.groupCustomer.customize === '0' || this.groupAgent.customize === '0') {
          if (this.groupCustomer.customize === '0') {
            this.groupCustomer.customize = ''
          }
          if (this.groupAgent.customize === '0') {
            this.groupAgent.customize = ''
          }
          this.$message.error(this.$t('validate.disagreeNumber'))
          return
        }
        let groupCustomer = deepClone(this.groupCustomer)
        let groupAgent = deepClone(this.groupAgent)
        let data = {}
        if (groupCustomer.customize) {
          data.visitorsReply = parseInt(groupCustomer.customize)
          data.visitorsReply = `${data.visitorsReply}__${this.$t('webchat.visitor')}:${data.visitorsReply}${this.$t('webchat.minutesAgo')}`
        }
        if (groupAgent.customize) {
          data.clientReply = parseInt(groupAgent.customize)
          data.clientReply = `${data.clientReply}__${this.$t('public.agent')}:${data.clientReply}${this.$t('webchat.minutesAgo')}`
        }
        groupCustomer.list.forEach((item, index) => {
          if (item.checked) {
            data.visitorsReply = `${5 * (index + 1)}__${this.$t('webchat.visitor')}:${item.name}`
          }
        })
        groupAgent.list.forEach((item, index) => {
          if (item.checked) {
            if (index === 6) {
              data.unReply = `${true}__${item.name}`
            } else {
              data.clientReply = `${5 * (index + 1)}__${this.$t('public.agent')}:${item.name}`
            }
          }
        })
        let flag = false
        console.log(data)
        this.$emit('timeSearch', data, flag)
        document.getElementsByTagName('body')[0].click()
      },
      changeCustomerLabel (index, ischecked) {
        if (ischecked) {
          this.groupCustomer.list.forEach((item) => {
            item.checked = false
          })
          this.groupCustomer.list[index].checked = true
          this.groupCustomer.customize = ''
        }
      },
      changeAgentLabel (index, ischecked) {
        if (index === 6) {
          this.groupAgent.list[index].checked = ischecked
          return
        }
        if (ischecked) {
          this.groupAgent.list.forEach((item, index) => {
            if (index !== 6) {
              item.checked = false
            }
          })
          this.groupAgent.list[index].checked = true
          this.groupAgent.customize = ''
        }
      },
      getAllCheck () {
        return this.groupCallLabel.filter(item => item.checked).map(item => item._id)
      }
    },
    components: {
      noviceBoot
    },
    mounted () {
      console.log('timeSearch Mounted')
      let currentUser = this.$store.state.session.user.loginName + '@' + this.$store.state.session.account.name
      let sortType = window.localStorage.getItem(currentUser + '/sortType') || 'lastCustomerMsgTimeStamp'
      this.handleChangeListSort(sortType)
    },
    beforeMount () {
//       todo 测试主动会话后台接口
/*    let ubaSession = null
       let that = this
       this.$store.dispatch('getSessionsByAccount', {pageSize: 10, page: 1}).then(() => {
       ubaSession = that.$store.state.webchat.inviteUbaSessionList.list[0]
       if (ubaSession) {
       return that.$store.dispatch('getMoreTrack', {sid: ubaSession._id})
       }
       }).then(() => {
       let sessionIds = []
       if (ubaSession) {
       sessionIds.push(ubaSession._id)
       let inviteMessage = '邀请语13213123'
       that.$store.dispatch('inviteCustomers', {sessionIds, inviteMessage})
       }
       })
       */
      let self = this
      this.$store.dispatch('getCache', {type: 'channelGlobalSet'}).then((res) => {
        innerHtmlChannelColor(self)
        if (res) {
          this.sessionInvitation = res.sessionInvitation ? res.sessionInvitation : ''
          if (res.custIntentionRule) {
            let cust = {name: this.$t('webchat.customerIntention'), value: 'custIntention', disabled: false}
            this.ListSortTypes.push(cust)
          } else {
            let cust = {name: this.$t('webchat.customerIntention'), value: 'custIntention', disabled: true}
            this.ListSortTypes.push(cust)
          }
        }
      })
      this.ListSortType = 'startWaitTimerStamp'
      // 获取最新呼吸灯是否展示
      this.updateGuidanceSuccess()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .sessionType_title
    font-size 12px
  .noticeOne
    position absolute
    top -10px
    right 89px
  .noticeTwo
    position absolute
    top -10px
    right 59px
  .webchatLimitSelect
    width 86px
    float right
    margin-right 20px
  .dropActive
    color $c-main
    background #e4e8f1
  .ListdropItem
    width 140px
  .high
    text-align right
    .searchButton
      color $cf-level4
      /*float right*/
      margin-right 10px
      margin-left 0px
  .high-ranking-search
    padding 10px 0 10px 10px
    font-size 0
    .time_search_box
      display flex
      color $cf-level2
      .flex3
        flex 3
        .groupLi
          display inline-block
          margin 0 20px 10px 0
          float left
          input[type='text']
            margin-right 6px
            border-color $c-border1
            color $cf-gray3
        .groupLiText
          color $cf-gray3
        input
          border 1px solid $c-border1
          border-radius 2px
          height 32px
          box-sizing border-box
          text-align center
          font-size 12px
  .el-form--inline
    .el-form-item
      margin-bottom 16px;
      margin-right 20px
      width 192px
    .add-width
      width 384px
      margin-right 40px
      .el-form-item__content
        .el-date-editor
          height 30px
          width 384px
    .minus-width
      width 0px
      .el-form-item__content
        .el-date-editor
          height 30px
          width 384px
    .all-width
      width 100%
      .el-form-item__content
        .el-date-editor
          height 30px
          width 100%
    /*  div:nth-child(5n)
    margin-right 0*/
    .dotted
      width 100%
      border thin dashed $c-border1
      margin-bottom 30px
    .solid
      width 100%
      border thin solid #e6e6e6
    .btn-group
      padding 13px 0 5px 0
      text-align center
    .icon-sousuo
      float right
  .label-box
    position relative
    float left
    height 32px
    input
      sing-inp()
    input:checked+span
      sing-sped()
    input+span
      sing-sp()
      min-width 56px
      margin 0
    input:checked+span
      &:after
        sing-af()
      &:before
        sing-be()
  .el-form-item.btn-group
    width 100%
    margin-bottom 0
    padding-bottom 0
  .high
    .iconfont
      font-size 12px
      /*-webkit-font-smoothing auto*/
      color $c-main
      span
        margin-left 5px
        vertical-align middle
    .iconfont:before
      font-size 18px
      vertical-align middle
  .search_title
    margin-bottom 10px
    color $cf-gray1
  .el-button
    padding 0
</style>
